package com.zhu.salesmanagement.network;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.zhu.salesmanagement.R;
import com.zhu.salesmanagement.SalesApplication;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CustomerItem;
import com.zhu.salesmanagement.models.CustomerShelfsItem;
import com.zhu.salesmanagement.models.ProductCategoryItem;
import com.zhu.salesmanagement.models.RemindMsgItem;
import com.zhu.salesmanagement.models.SyncProductItem;
import com.zhu.salesmanagement.models.SyncTaskItem;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.SyncView;

/**
 * 同步
 */
public class SyncData {

	private static final int PUTPHONEMAXCOUNT = 20;

	private static final int SETUP_GETPC = 1; //产品大类
	private static final int SETUP_GETPRODUCT = 2; //产品
	private static final int SETUP_GETCUSTOMER = 3; //客户
	private static final int SETUP_GETCSHELF = 4;//货架信息
	private static final int SETUP_UPDATEPC = 5; //产品大类更新
	private static final int SETUP_GETTASK = 6; //拜访任务
	private static final int SETUP_GETREMIND = 7; //提醒
	private static final int SETUP_PUTDTASKACTUAL = 8; //上传拜访任务
	private static final int SETUP_PUTCUSTOMERSHELF = 9; //上传货架信息
	private static final int SETUP_PUTDTASKACTUALCRC = 10; //上传CRC
	private static final int SETUP_PUTDTASKACTUALOTHER = 11; //上传重要和竟品信息
	private static final int SETUP_PUTNEWADDEDSTORES = 12; //上传新增们点
	private static final int SETUP_PUTCUTOMERCOLSE = 13;//上传歇业们点
	private static final int SETUP_PUTSTOREPROPERTY = 14; //上传门店属性
	private static final int SETUP_PUTDTASKACTUALPHOTO = 15;
	private static final int SETUP_PUTCOMPELE = 16; //同步完成

	//同步数据保存列表
	private ArrayList<ProductCategoryItem> mPClist = null;
    private ArrayList<SyncProductItem> mPlist = null;
    private ArrayList<CustomerItem> mCustomerList = null;
    private ArrayList<CustomerShelfsItem> mCSlist = null;
    private ArrayList<CustomerShelfsItem> mUpdateCSlist = null;
    private ArrayList<SyncTaskItem> mTaskList = null;
    private ArrayList<RemindMsgItem> mRemindList = null;
    private List<Object> mStorePropertyList = new ArrayList<Object>();
    private List<Object> mStorePhoteList = null;

    private Context mContext = null;
    private int mConnectStep = -1;
    private Handler mHandler = null;
    private int retryCount = 0;
    private int mPutCount = 0;
    private int mTotalCount = 0;
    private CustomerShelfData mCustomerShelfData = null;
    private String[] mProjection = new String[]{ "_id" };
    private boolean isAddSyncSuccessRemind = false; 
    private long mNetworkTime = 0;

    /**
     * 构造函数
     * @param context 上下文
     * @param handler 结果
     */
    public SyncData(Context context, Handler handler){
    	mContext = context;
    	mHandler = handler;
    }

    /**
     * 开始同步
     */
    public void startSync(){
    	if(mConnectStep == -1){
    		isAddSyncSuccessRemind = false;
    		resetData();
    		updateisFirst();
    		if(mCustomerShelfData == null){
    			mCustomerShelfData = new CustomerShelfData(mContext, Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID);
    		}
    		mCustomerShelfData.parseData();
    		mStorePhoteList = PostData.getStorePhotos(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mContext);
    		mPutCount = 0;
    		mTotalCount = 0;
    		requestNetworkTime();
    	}
    }

    /**
     * 重置数据
     */
    private void resetData(){
    	if(mPClist != null){
    		mPClist.clear();
    		mPClist = null;
    	}
    	if(mPlist != null){
    		mPlist.clear();
    		mPlist = null;
    	}
    	if(mCustomerList != null){
    		mCustomerList.clear();
    		mCustomerList = null;
    	}
    	if(mCSlist != null){
    		mCSlist.clear();
    		mCSlist = null;
    	}
    	if(mUpdateCSlist != null){
    	    mUpdateCSlist.clear();
    	    mUpdateCSlist = null;
    	}
    	if(mTaskList != null){
    		mTaskList.clear();
    		mTaskList = null;
    	}
    	if(mRemindList != null){
    		mRemindList.clear();
    		mRemindList = null;
    	}
    	if(mStorePhoteList != null){
    	    mStorePhoteList.clear();
    	    mStorePhoteList = null;
    	}
    	if(mStorePropertyList != null){
    	    mStorePropertyList.clear();
    	}
    }

    /**
     * 重试连接
     */
    private void retryConnect(){
    	switch(mConnectStep){
    		case SETUP_GETPC:
    			getProductCategory();
    			break;
    		case SETUP_GETPRODUCT:
    			getProduct();
    			break;
    		case SETUP_GETCUSTOMER:
    			getCustomer();
    			break;
    		case SETUP_GETCSHELF:
    			getProductCategoryAndCustomerShelfOfCustomers();
    			break;
    		case SETUP_UPDATEPC:
    		    updateProductCategory();
    		    break;
    		case SETUP_GETTASK:
    			getMyTaskList();
    			break;
    		case SETUP_GETREMIND:
    			getRemindMSG();
    			break;
    		case SETUP_PUTDTASKACTUAL:
    			putDatingTaskActual();
    			break;
    		case SETUP_PUTCUSTOMERSHELF:
    			putCustomerShelf();
    			break;
    		case SETUP_PUTDTASKACTUALCRC:
    			putDatingTaskActualCRC();
    			break;
    		case SETUP_PUTDTASKACTUALOTHER:
    			putDatingTaskActualOther();
    			break;
    		case SETUP_PUTNEWADDEDSTORES:
    			putCustomerTemp();
    			break;
    		case SETUP_PUTCUTOMERCOLSE:
    			putCustomerClose();
    			break;
    		case SETUP_PUTSTOREPROPERTY:
    		    putStoreProrery();
    		    break;
    		case SETUP_PUTDTASKACTUALPHOTO:
    			putDatingTaskActualPhoto();
    			break;
    		case SETUP_PUTCOMPELE:
    			putCompleted();
    			break;
    	}
    }

    /**
     * 是否第一次同步
     */
    private void updateisFirst(){
    	Cursor cursor = null; 
		try {
			cursor = mContext.getContentResolver().query(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, mProjection,
					null, null, null);
			if (cursor != null && cursor.getCount() > 0) {
				Util.isFirst = false;
			}else{
				Util.isFirst = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Util.isFirst = true;
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}
    }

    /**
     * getProductCategory
     */
    private void getProductCategory(){
    	mConnectStep = SETUP_GETPC;
    	Log.e("zhu",Util.mVerifyUserResult.id +","+ Util.mVerifyUserResult.mUUID);
    	mHandler.sendEmptyMessage(SyncView.SYNC_1);
		PostMethod.requesProductCategory(Util.mVerifyUserResult.id,
				Util.mVerifyUserResult.mUUID, true, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						mPClist = ParseData.parseProductCategory(result, mContext);
						if(mPClist != null){
							retryCount = 0;
							getProduct();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getProduct
     */
    private void getProduct(){
    	mConnectStep = SETUP_GETPRODUCT;
		PostMethod.requesProducts(Util.mVerifyUserResult.id,
				Util.mVerifyUserResult.mUUID, true, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						mPlist = ParseData.parseProducts(result, mContext);
						if(mPlist != null){
							mHandler.sendEmptyMessage(SyncView.SYNC_2);
							retryCount = 0;
							getCustomer();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getCustomer
     */
    private void getCustomer(){
    	mConnectStep = SETUP_GETCUSTOMER;

		PostMethod.requesCustomer(Util.mVerifyUserResult.id,
				Util.mVerifyUserResult.mUUID, true, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						mCustomerList = ParseData.parseCustomer(result, mContext);
						if(mCustomerList != null){
							retryCount = 0;
							getProductCategoryAndCustomerShelfOfCustomers();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getProductCategoryAndCustomerShelfOfCustomers
     */
    private void getProductCategoryAndCustomerShelfOfCustomers(){
        if(Util.isFirst){
            mConnectStep = SETUP_GETCSHELF;
            PostMethod.requesCustomerShelfs(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, true, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                            mCSlist = ParseData.parseCustomerShelfs(result, mContext);
                            if(mCSlist != null){
                                retryCount = 0;
                                mHandler.sendEmptyMessage(SyncView.SYNC_3);
                                getMyTaskList();
                            }else{
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
        }else{
            updateProductCategory();
        }
    }

    /**
     * updateProductCategory
     */
    private void updateProductCategory(){
        mConnectStep = SETUP_UPDATEPC;
        PostMethod.requesUpdateCustomerPC(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, true, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                            mUpdateCSlist = ParseData.parseUpdateCustomerPCs(result, mContext);
                            if (mUpdateCSlist != null) {
                                retryCount = 0;
                                mHandler.sendEmptyMessage(SyncView.SYNC_3);
                                getMyTaskList();
                            } else {
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 获取清单拜访任务
     */
    private void getMyTaskList(){
    	mConnectStep = SETUP_GETTASK;
    	if(!Util.isEndVisit(mContext)){
    	    if(Actions.DEBUG){
    	        Log.e("zhu","isEndVisit=false");
    	    }
            mHandler.sendEmptyMessage(SyncView.SYNC_4);
            getRemindMSG();
            return;
    	}
		PostMethod.requesMyTaskList(Util.mVerifyUserResult.id,
				Util.mVerifyUserResult.mUUID, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						mTaskList = ParseData.parseMyTaskList(result, mContext);
						if(mTaskList != null){
							retryCount = 0;
							mHandler.sendEmptyMessage(SyncView.SYNC_4);
							getRemindMSG();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }
    
    /**
     * getRemindMSG
     */
    private void getRemindMSG(){
    	mConnectStep = SETUP_GETREMIND;
    	PostMethod.requesRemindMsg(Util.mVerifyUserResult.id,
				Util.mVerifyUserResult.mUUID, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						mRemindList = ParseData.parseRemindMsg(result, mContext);
						if(mRemindList != null){
//							if(mCustomerShelfData == null){
//								mCustomerShelfData = new CustomerShelfData(mContext, Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID);
//							}
//							mCustomerShelfData.parseData();
							retryCount = 0;
							putDatingTaskActual();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActual
     */
    private void putDatingTaskActual(){
    	mConnectStep = SETUP_PUTDTASKACTUAL;
    	mHandler.sendEmptyMessage(SyncView.SYNC_5);
    	Object[] object = mCustomerShelfData.getVisitedTaskObject();
    	if(Actions.DEBUG){
    		Log.e("zhu","putDatingTaskActual="+object);
    	}
    	if(object == null){
    		putCustomerShelf();
    		return;
    	}
    	PostMethod.postDatingTaskActual(object, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						boolean isSuccess = ParseData.parsePostData(result);
						if(isSuccess){
							retryCount = 0;
							putCustomerShelf();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putCustomerShelf
     */
    private void putCustomerShelf(){
    	mConnectStep = SETUP_PUTCUSTOMERSHELF;
    	Object[] object = mCustomerShelfData.getShelfObject();
    	if(Actions.DEBUG){
    		Log.e("zhu","putCustomerShelf="+object);
    	}
    	if(object == null){
    		putDatingTaskActualCRC();
    		return;
    	}
    	PostMethod.postCustomerShelf(object, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						boolean isSuccess = ParseData.parsePostData(result);
						if(isSuccess){
							retryCount = 0;
							putDatingTaskActualCRC();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualCRC
     */
    private void putDatingTaskActualCRC(){
    	mConnectStep = SETUP_PUTDTASKACTUALCRC;
    	Object[] object = mCustomerShelfData.getCRCObject();
    	if(Actions.DEBUG){
    		Log.e("zhu","putDatingTaskActualCRC="+object);
    	}
    	if(object == null){
    		putDatingTaskActualOther();
    		return;
    	}
    	PostMethod.postDatingTaskActualCRC(object, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						boolean isSuccess = ParseData.parsePostData(result);
						if(isSuccess){
							retryCount = 0;
							putDatingTaskActualOther();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putDatingTaskActualOther
     */
    private void putDatingTaskActualOther(){
    	mConnectStep = SETUP_PUTDTASKACTUALOTHER;
    	Object[] object = mCustomerShelfData.getOtherObject();
    	if(Actions.DEBUG){
    		Log.e("zhu","putDatingTaskActualOther="+object);
    	}
    	if(object == null){
    		putCustomerTemp();
    		return;
    	}
    	PostMethod.postDatingTaskActualOther(object, new XMLRPCMethodCallback() {
					public void callFinished(int status, Object result) {
						boolean isSuccess = ParseData.parsePostData(result);
						if(isSuccess){
							retryCount = 0;
							putCustomerTemp();
						}else{
							syncFail();
						}
					}
				}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putCustomerTemp
     */
    private void putCustomerTemp(){
    	mConnectStep = SETUP_PUTNEWADDEDSTORES;
    	mHandler.sendEmptyMessage(SyncView.SYNC_6);
    	Object[] object = PostData.getNewAddStores(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mContext, mStorePropertyList);
    	if(Actions.DEBUG){
    		Log.e("zhu","putCustomerTemp="+object);
    	}
    	if(object == null){
    		putCustomerClose();
    		return;
    	}
    	PostMethod.postNewAddedStores(object, new XMLRPCMethodCallback() {
			public void callFinished(int status, Object result) {
				boolean isSuccess = ParseData.parsePostData(result);
				if(isSuccess){
					retryCount = 0;
					putCustomerClose();
				}else{
					syncFail();
				}
			}
		}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putCustomerClose
     */
    private void putCustomerClose(){
    	mConnectStep = SETUP_PUTCUTOMERCOLSE;
    	if(Actions.DEBUG){
    		Log.e("zhu","putCustomerClose");
    	}
    	mHandler.sendEmptyMessage(SyncView.SYNC_7);
    	Object[] object = PostData.getCustomerClosedList(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mContext);
    	if(object == null){
    	    putStoreProrery();//putCompleted();
    		return;
    	}
    	PostMethod.postCustomerClose(object, new XMLRPCMethodCallback() {
			public void callFinished(int status, Object result) {
				boolean isSuccess = ParseData.parsePostData(result);
				if(isSuccess){
					retryCount = 0;
					putStoreProrery();//putCompleted();
				}else{
					syncFail();
				}
			}
		}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putStoreProrery
     */
    private void putStoreProrery(){
        mConnectStep = SETUP_PUTSTOREPROPERTY;
        if(Actions.DEBUG){
            Log.e("zhu","putStoreProrery");
        }
        if(mStorePropertyList.size() > 0){
            PostMethod.postStoreProperty(new Object[]{ Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mStorePropertyList }, new XMLRPCMethodCallback() {
                public void callFinished(int status, Object result) {
                    boolean isSuccess = ParseData.parsePostData(result);
                    if(isSuccess){
                        retryCount = 0;
                        putDatingTaskActualPhoto();
                    }else{
                        syncFail();
                    }
                }
            }, SalesApplication.mApplicaton.getXMLRPCClient());
        }else{
        	putDatingTaskActualPhoto();
        }
    }

    /**
     * putDatingTaskActualPhoto
     */
    private void putDatingTaskActualPhoto(){
        mConnectStep = SETUP_PUTDTASKACTUALPHOTO;
        Object[] object = null;
        if(mStorePhoteList != null && mStorePhoteList.size() > 0){
            mTotalCount = mStorePhoteList.size() / PUTPHONEMAXCOUNT;
            if(mStorePhoteList.size() % PUTPHONEMAXCOUNT != 0){
                mTotalCount++;
            }
            if(mStorePhoteList.size() > PUTPHONEMAXCOUNT){
                List<Object> list = new ArrayList<Object>();
                if(mPutCount < mTotalCount -1){
                    list.addAll(mStorePhoteList.subList(PUTPHONEMAXCOUNT * mPutCount, (mPutCount + 1) * PUTPHONEMAXCOUNT));
                }else{
                    list.addAll(mStorePhoteList.subList(PUTPHONEMAXCOUNT * mPutCount, mStorePhoteList.size()));
                }
                object = new Object[]{ Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, list};
            }else{
                object = new Object[]{ Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, mStorePhoteList};
            }
        }
        if(Actions.DEBUG){
            Log.e("zhu","putDatingTaskActualPhoto="+object);
        }
        if(object == null){
            putCompleted();
            return;
        }
        PostMethod.putDatingTaskActualPhoto(object, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                boolean isSuccess = ParseData.parsePostData(result);
                if(isSuccess){
                    mPutCount++;
                    if(mPutCount >= mTotalCount){
                        retryCount = 0;
                        putCompleted();
                    }else{
                        putDatingTaskActualPhoto();
                    }
                }else{
                    syncFail();
                }
            }
        }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * putCompleted
     */
    private void putCompleted(){
    	mConnectStep = SETUP_PUTCOMPELE;
    	if(Actions.DEBUG){
    		Log.e("zhu","putCompleted");
    	}
    	Object[] object = new Object[]{ Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, new Date(Util.mVerifyUserResult.mStartSyncTime)};
    	PostMethod.postCompeleted(object, new XMLRPCMethodCallback() {
			public void callFinished(int status, Object result) {
				boolean isSuccess = ParseData.parsePostData(result);
				if(isSuccess){
					retryCount = 0;
					syncSuccessEnd();
				}else{
					syncFail();
				}
			}
		}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 同步成功
     */
    private void syncSuccessEnd(){
    	if(Actions.DEBUG){
    		Log.e("zhu","syncSuccessEnd");
    	}
    	isAddSyncSuccessRemind = Util.isEndVisit2(mContext);
    	deletePutData();
    	saveSyncData();
    	mConnectStep = -1;
    	retryCount = 0;
    	Util.isFirst = false;
    	mHandler.sendEmptyMessage(SyncView.SYNC_SUCCESSEND);
    }

    /**
     * 同步失败
     */
    private void syncFail(){
    	if(Actions.DEBUG){
    		Log.e("zhu","syncFail="+mConnectStep);
    	}
    	if(retryCount < 3){
    		retryCount++;
    		retryConnect();
    	}else{
    		retryCount = 0;
    		mConnectStep = -1;
    		mHandler.sendEmptyMessage(SyncView.SYNC_FAILEDEND);
    	}
    }

    private void requestNetworkTime(){
        if(Actions.DEBUG){
            Log.e("zhu","requestNetworkTime");
        }
        mNetworkTime = 0;
        PostMethod.requestNetworkTime(Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                mNetworkTime  = ParseData.parseNetworkTime(result);
                getProductCategory();
            }
        },SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 保存同步数据
     */
    private void saveSyncData(){

    	//saveCPlist();

    	if(mPClist != null){
    		String deletepcwhere = "";
    		for(int i = 0; i < mPClist.size(); i++){
    			ProductCategoryItem item = mPClist.get(i);
    			if(item.mType == ParseData.UPDATE){
    				long dbid = getDatabaseId(SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID + " = \"" + item.mProductCategoryId +"\"");
    				ContentValues values = new ContentValues();
                    values.put(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME, item.mProductCategoryName);
                    if(dbid == -1){
                    	values.put(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID, item.mProductCategoryId);
                    	mContext.getContentResolver().insert(SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }else{
                    	mContext.getContentResolver().update(SalesSettings.ProductCategoryColumns.getContentUri(dbid, false), values, null, null);
                    }
    			}else{
    				if(deletepcwhere.length() == 0){
    					deletepcwhere = SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.mProductCategoryId + "\"";
    				}else{
    					deletepcwhere += " or " + SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.mProductCategoryId + "\"";
    				}
    			}
    		}
    		if(deletepcwhere.length() > 1){
    			mContext.getContentResolver().delete(SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, deletepcwhere, null);
    		}
    	}

    	if(mPlist != null){
    		String deletepwhere = "";
    		for(int i = 0; i < mPlist.size(); i++){
    			SyncProductItem item = mPlist.get(i);
    			if(item.mType == ParseData.UPDATE){
    				long dbid = getDatabaseId(SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.ProductsColumns.PRODUCT_ID + " = \"" + item.sProductID +"\"");
    				ContentValues values = new ContentValues();
                    values.put(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID, item.sProductCategoryID);
                    values.put(SalesSettings.ProductsColumns.PRODUCT_NAME, item.sProductShortName);
                    values.put(SalesSettings.ProductsColumns.PRODUCT_SORT, item.iSort);
                    if(dbid == -1){
                    	values.put(SalesSettings.ProductsColumns.PRODUCT_ID, item.sProductID);
                    	mContext.getContentResolver().insert(SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }else{
                    	mContext.getContentResolver().update(SalesSettings.ProductsColumns.getContentUri(dbid, false), values, null, null);
                    }
    			}else{
    				if(deletepwhere.length() == 0){
    					deletepwhere = SalesSettings.ProductsColumns.PRODUCT_ID +" = \"" + item.sProductID + "\"";
    				}else{
    					deletepwhere += " or " + SalesSettings.ProductsColumns.PRODUCT_ID +" = \"" + item.sProductID + "\"";
    				}
    			}
    		}
    		if(deletepwhere.length() > 1){
    			mContext.getContentResolver().delete(SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, deletepwhere, null);
    		}    		
    	}

		String deletecwhere = "";

    	if(mCustomerList != null){
    		for(int i = 0; i < mCustomerList.size(); i++){
    			CustomerItem item = mCustomerList.get(i);
    			if(item.mType == ParseData.UPDATE){
    			  long dbid = getDatabaseId(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.CustomerSColumns.CUSTOMER_ID + " = \"" + item.sCustomerID +"\"");
                  ContentValues values = new ContentValues();
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_NAME, item.sCustomerName);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS, item.sCustomerAddress);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_CONTACT, item.sCustomerContractor);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_TEL, item.sTel);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_DEALTID, item.sDealtEmployeeID);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE, item.iVisitCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LEVEL, item.sStoreLevel);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_TYPE, item.sStoreCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LAT, item.sLatitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LNG, item.sLongitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY, item.iProperty);
                  if(dbid == -1){
                      values.put(SalesSettings.CustomerSColumns.CUSTOMER_ID, item.sCustomerID);
                      mContext.getContentResolver().insert(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, values);
                  }else{
                	  mContext.getContentResolver().update(SalesSettings.CustomerSColumns.getContentUri(dbid, false), values, null, null);
                  }
    			}else{
    				if(deletecwhere.length() == 0){
    					deletecwhere = SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + item.sCustomerID + "\"";
    				}else{
    					deletecwhere += " or " + SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + item.sCustomerID + "\"";
    				}
    			}
    		}
    		if(deletecwhere.length() > 1){
    			mContext.getContentResolver().delete(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, deletecwhere, null);
    		}
    	}

    	if(mCSlist != null){
    		for(int i = 0; i < mCSlist.size(); i++){
    			CustomerShelfsItem item = mCSlist.get(i);
    			String temWhere = SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \"" + item.customerId +"\" and " + 
    			SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \"" + item.sProductCategoryID +"\"";
    			long dbid = getDatabaseId(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, temWhere);
    			ContentValues values = new ContentValues();
    			values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT, item.iShelfCount);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA, item.iShelfArea);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER, item.iShelfLayer);
    			if(dbid == -1){
                    values.put(SalesSettings.ProductShelfsColumns.CUSTOMER_ID, item.customerId);
                    values.put(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID, item.sProductCategoryID);
                    mContext.getContentResolver().insert(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, values);
    			}else{
    			    mContext.getContentResolver().update(SalesSettings.ProductShelfsColumns.getContentUri(dbid, false), values, null, null);
    			}
    		}
    	}
    	if(deletecwhere.length() > 1){
			mContext.getContentResolver().delete(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, deletecwhere, null);
		}

    	String deletepcwhere = "";

    	if(mUpdateCSlist != null){
    	    for (int i = 0; i < mUpdateCSlist.size();i++){
    	        CustomerShelfsItem item = mUpdateCSlist.get(i);
    	        if(item.type == ParseData.UPDATE){
    	            String temWhere = SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \"" + item.customerId +"\" and " + 
                    SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \"" + item.sProductCategoryID +"\"";
                    long dbid = getDatabaseId(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, temWhere);
                    if(dbid == -1){
                        ContentValues values = new ContentValues();
                        values.put(SalesSettings.ProductShelfsColumns.CUSTOMER_ID, item.customerId);
                        values.put(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID, item.sProductCategoryID);
                        mContext.getContentResolver().insert(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }
    	        }else{
    	            if(deletepcwhere.length() == 0){
    	                deletepcwhere = SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \'" + item.customerId + "\' and " + 
    	                SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \'" + item.sProductCategoryID +"\'";
    	            }else{
    	                deletepcwhere += " or " + SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \'" + item.customerId + "\' and " + 
                        SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \'" + item.sProductCategoryID +"\'";
    	            }
    	        }
    	    }
    	}

    	if(deletepcwhere.length() > 1){
            mContext.getContentResolver().delete(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, deletepcwhere, null);
        }

    	if(mTaskList != null){
    		for(int i = 0; i < mTaskList.size(); i++){
    			SyncTaskItem item = mTaskList.get(i);
    			ContentValues values = new ContentValues();
                values.put(SalesSettings.VisitedStoresColumns.EMPLOYEEID, item.sEmployeeID);
                values.put(SalesSettings.VisitedStoresColumns.TASKID, item.iDatingTaskID);
                values.put(SalesSettings.VisitedStoresColumns.TASTDATE, item.dPlanningDate);
                values.put(SalesSettings.VisitedStoresColumns.AEMPLOYEEID, item.sAssignedEmployeeID);
                values.put(SalesSettings.VisitedStoresColumns.ITEMNO, item.iItemNo);
                values.put(SalesSettings.VisitedStoresColumns.STOREID, item.sCustomerID);
                values.put(SalesSettings.VisitedStoresColumns.VISITCATEGOR, item.iVisitCategory);
                values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID, Util.getDatingTaskActualID(Util.mVerifyUserResult.id, item.sCustomerID, mNetworkTime));
                mContext.getContentResolver().insert(SalesSettings.VisitedStoresColumns.CONTENT_URI_NO_NOTIFICATION, values);
    		}
    	}

    	if(mRemindList != null){
    		for(int i = 0; i < mRemindList.size(); i++){
    			RemindMsgItem item = mRemindList.get(i);
				ContentValues values = new ContentValues();
				values.put(SalesSettings.RemindsColumns.EMPLOYEEID, item.sEmployeeID);
				values.put(SalesSettings.RemindsColumns.MESSAGEID, item.iRemindMSGID);
				values.put(SalesSettings.RemindsColumns.TEXT, item.sRemindMSGText);
				values.put(SalesSettings.RemindsColumns.TIME, item.dRemindTime);
				values.put(SalesSettings.RemindsColumns.TYPE, item.iCycleCategory);
				values.put(SalesSettings.RemindsColumns.CUSTOMERID, item.sCustomerID);
				values.put(SalesSettings.RemindsColumns.DEADTIME, item.dDeadTime);
				if(item.sCustomerID == null || item.sCustomerID.trim().length() == 0){
	                String eventid = Actions.addEvent(mContext,
	                        item.sRemindMSGText, "", "",
	                        Long.parseLong(item.dRemindTime),
	                        Long.parseLong(item.dRemindTime) + 1000 * 60 * 60, 3,
	                        Integer.parseInt(item.iCycleCategory));
	                if(Actions.DEBUG){
	                    Log.e("zhu", "eventid=" + eventid);
	                }
	                values.put(SalesSettings.RemindsColumns.EVENTID, eventid);
				}
				mContext.getContentResolver().insert(SalesSettings.RemindsColumns.CONTENT_URI, values);
    		}
    	}

    	if(mStorePropertyList.size() > 0 && Util.isEndVisit(mContext)){
    	    for(int i = 0; i < mStorePropertyList.size(); i++){
    	        Map map = (Map)mStorePropertyList.get(i);
    	        String cid = (String)map.get("sCustomerID");
    	        ContentValues values = new ContentValues();
                values.put(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY, 0);
                String where = SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \'" + cid + "\'";
                mContext.getContentResolver().update(SalesSettings.CustomerSColumns.CONTENT_URI, values, where, null);
    	    }
    	}

    	if(isAddSyncSuccessRemind){
    		ContentValues values = new ContentValues();
    		Date now=new Date();
    		SimpleDateFormat temp=new SimpleDateFormat("yyyy-MM-dd kk:mm");
    		String time=temp.format(now);
    		long deadtime = System.currentTimeMillis() + 72 * 60 * 60 *1000;
    		String text = mContext.getResources().getString(R.string.syncsuccessremind, time);
			values.put(SalesSettings.RemindsColumns.TEXT, text);
			values.put(SalesSettings.RemindsColumns.DEADTIME, "" + deadtime);
			mContext.getContentResolver().insert(SalesSettings.RemindsColumns.CONTENT_URI, values);
    	}
    }

    private void saveCPlist(){
    	List<CustomerShelfsItem> list = mCustomerShelfData.getSaveCPlist();
    	String where = "";
    	if(list != null){
    		for(int i = 0; i < list.size(); i++){
    			CustomerShelfsItem item = list.get(i);
    			ContentValues values = new ContentValues();
    			values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT, item.iShelfCount);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA, item.iShelfArea);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER, item.iShelfLayer);
                where = SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \'" +  item.customerId + "\' and " +
                		SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \'" + item.sProductCategoryID +"\'";
                mContext.getContentResolver().update(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, values, where, null);
    		}
    	}
    }
    private long getDatabaseId(Uri uri, String where){
    	long id = -1;
    	Cursor cursor = null;
    	try{
    		cursor = mContext.getContentResolver().query(uri, mProjection, where, null, null);
    		if(cursor.getCount() > 0 && cursor.moveToFirst()){
    			id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		if(cursor != null){
    			cursor.close();
    			cursor = null;
    		}
    		return id;
    	}
    }

    /**
     * 删除上传数据
     */
    public void deletePutData(){
    	PostData.deleteStorePhotos(mContext);
    	PostData.deleteAllNewAddedStores(mContext);
    	PostData.deleteAllRemindsData(mContext);
    	mCustomerShelfData.delteSqData();
    }

    public void detory(){
    	resetData();
    	if(mCustomerShelfData != null){
    		mCustomerShelfData.destory();
    		mCustomerShelfData = null;
    	}
    }
}
